package com.mai4j.maiadmin.service.impl;

import com.mai4j.maiadmin.service.QueryService;
import com.mai4j.maiadmin.support.JooqProvider;
import com.mai4j.maiadmin.support.cache.CacheName;
import org.jooq.DSLContext;
import org.jooq.Select;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Service
public class QueryServiceImpl implements QueryService {

    /**
     * 分页记录总数，放入flash缓存中，总数小于100并且耗时小于 20 毫秒的不缓存
     * paginate:count:sha256(SQL)
     * <br />
     *
     * @param query query
     * @return int
     */
    @Cacheable(value = CacheName.FLASH,
            key = "'paginate:count:' + T(com.mai4j.maiadmin.misc.CacheUtils).genKey(#query)",
            unless = "#result.count < 100 && #result.elapsed < 20 ")
    public CountResult fetchCount(Select<?> query) {
        long st = System.currentTimeMillis();
        DSLContext dsl = JooqProvider.dsl();
        return new CountResult()
                .setCount(dsl.fetchCount(query))
                .setElapsed(System.currentTimeMillis() - st);
    }
}
